<template>
  <div class="drawerMain">
    <el-form
      ref="formData"
      label-position="top"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="form"
    >
      <el-form-item
        label="规则名称"
        prop="name"
      >
        <el-input
          v-model="formData.name"
          placeholder="请输入规则名称"
        ></el-input>
      </el-form-item>
      <el-form-item prop="vip_num">
        <div class="form_bac">
          <span class="bac_label">
            会员推荐
          </span>
          <el-input
            v-model="formData.vip_num"
            oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
            type="number"
            class="bac_input"
          ></el-input>
          <span>
            部后停止
          </span>
          <el-tooltip
            class="item"
            effect="dark"
            placement="top"
          >
            <div
              slot="content"
              class="tooltipLine"
            >
              <p>如短剧启用官方播放器，则</p>
              <p>1、【会员推荐n部后停止】此规则受官方播放器插件限制无法实现，会自动跳过此规则，按后续规则满足短剧列表显示</p>
              <p>2、如不满6部，则不显示推荐列表</p>
            </div>
            <i
              class="el-icon-question"
              style="margin-left:2px;font-size:16px;color:#86909C;"
            ></i>
          </el-tooltip>
        </div>
      </el-form-item>
      <div class="model_border">
        <div class="model_title">
          <span>
            推荐短剧
          </span>
          <el-tooltip
            class="item"
            effect="dark"
            placement="top"
          >
            <div slot="content">
              <p>按选中频道、标签且短剧标记为开启推荐的短剧，按满足条件剧id从大到小依次推荐</p>
            </div>
            <i
              style="color: #86909C;"
              class="el-icon-question"
            ></i>
          </el-tooltip>
        </div>
      </div>
      <el-form-item
        prop="gender_type"
        label="推荐频道"
      >
        <el-radio-group v-model="formData.gender_type">
          <el-radio label="1">男频</el-radio>
          <el-radio label="2">女频</el-radio>
          <el-radio label="3">其他</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        prop="playlet_tags"
        label="推荐标签"
      >
        <el-select
          v-model="formData.playlet_tags"
          clearable
          multiple
          collapse-tags
          style="width:100%;"
          placeholder="请选择标签"
          filterable
        >
          <el-option
            v-for="item in optionsList.tags"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <div class="model_border">
        <div class="model_title">
          <span>
            自定义推剧
          </span>
          <el-tooltip
            class="item"
            effect="dark"
            placement="top"
          >
            <div slot="content">
              <p>推荐完标签剧后，如设置自定义推荐剧，会继续推送自定义推荐剧</p>
            </div>
            <i
              style="color: #86909C;"
              class="el-icon-question"
            ></i>
          </el-tooltip>
        </div>
      </div>
      <div style="margin-bottom: 12px;">
        <el-select
          v-model="formData.custom_playlet"
          clearable
          style="width:100%;"
          placeholder="请选择"
          filterable
          remote
          :remote-method="onGetRecommendPlaylet"
          multiple
          collapse-tags
          value-key="value"
        >
          <el-option
            v-for="item in optionsList.custom_playlet"
            :key="item.value"
            :label="item.label"
            :value="item"
          >
          </el-option>
        </el-select>
      </div>
      <BiTable
        ref="table"
        row-key="id"
        :data="formData.custom_playlet"
        size="medium"
        :column="tableColums"
        fixed="sticky"
        fixed-offset="50"
        layout="total, prev, pager, next"
        :auto-scroll="false"
      >
        <template v-slot:label="{ row }">
          <div class="drag">
            <SvgIcon
              icon-class="drag2"
              class="drag"
              style="font-size: 14px; margin: -1px 3px 0 0; width: 20px"
            ></SvgIcon>
            {{ row.label }} / {{ row.value }}
          </div>
        </template>
        <template v-slot:zip="{ row }">
          <el-button
            type="text"
            size="medium"
            @click="onRemove(row.value)"
          >删除
          </el-button>
        </template>
      </BiTable>
    </el-form>
    <span class="dialog-footer rowFlex">
      <el-button
        class="btn"
        @click="close"
      >取 消</el-button>
      <el-button
        class="btn"
        type="primary"
        :loading="loading"
        @click="commitData"
      >确 定</el-button>
    </span>
  </div>
</template>

<script>
import { playlet_recommendSave } from '@/api/recommends'
import { commonData } from '@/api/common'
import draggable from 'vuedraggable'
import Sortable from 'sortablejs'
import SvgIcon from '@/components/SvgIcon/index.vue'
export default {
  components: {
    draggable,
    SvgIcon
  },
  props: {
    row: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      loading: false,
      formData: {
        id: '',
        name: '',
        vip_num: '',
        gender_type: '',
        playlet_tags: '',
        custom_playlet: []
      },
      rules: {
        name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
        vip_num: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
        gender_type: [{ required: true, message: '请选择频道', trigger: 'blur' }],
        playlet_tags: [{ required: true, message: '请选择标签', trigger: 'blur' }]
      },
      optionsList: {
        tags: [],
        custom_playlet: []
      },
      tableColums: [
        {
          label: '短剧名称',
          prop: 'label',
          slotScope: true
        },
        {
          label: '标签',
          prop: 'tags',
          render: (h, { row }) => {
            if (row.tags.length > 0) {
              return (
                <div style='display:flex;flex-wrap: wrap;'>
                  {row.tags.map((item) => {
                    return (
                      <span class='colorStatus' style='margin-left:5px;margin-top:5px;'>
                        <span class='success'> {item.tag_title} </span>
                      </span>
                    )
                  })}
                </div>
              )
            }
          },
          width: 150
        },
        {
          label: '操作',
          prop: 'zip',
          width: 70,
          slotScope: true
        }
      ]
    }
  },
  mounted() {
    if (this.row.open_type === 2) {
      const obj = JSON.parse(JSON.stringify(this.row))
      this.formData = {
        id: obj.id,
        name: obj.name,
        vip_num: obj.vip_num,
        gender_type: obj.gender_type,
        playlet_tags: obj.playlet_tags.map((item) => item.id * 1),
        custom_playlet: obj.custom_playlet
          .sort((max, min) => {
            return min.sort - max.sort
          })
          .map((item) => {
            return {
              value: item.id,
              tags: item.tags.map((it) => {
                return {
                  tag_title: it
                }
              }),
              label: item.title
            }
          })
      }
      this.optionsList.custom_playlet = obj.custom_playlet
        .sort((max, min) => {
          return max.sort - min.sort
        })
        .map((item) => {
          return {
            value: item.id,
            tags: item.tags.map((it) => {
              return {
                tag_title: it
              }
            }),
            label: item.title
          }
        })
    } else if (this.row.open_type === 3) {
      const obj = JSON.parse(JSON.stringify(this.row))
      this.formData = {
        id: '',
        name: obj.name,
        vip_num: obj.vip_num,
        gender_type: obj.gender_type,
        playlet_tags: obj.playlet_tags.map((item) => item.id * 1),
        custom_playlet: obj.custom_playlet
          .sort((max, min) => {
            return min.sort - max.sort
          })
          .map((item) => {
            return {
              value: item.id,
              tags: item.tags.map((it) => {
                return {
                  tag_title: it
                }
              }),
              label: item.title
            }
          })
      }
      this.optionsList.custom_playlet = obj.custom_playlet
        .sort((max, min) => {
          return max.sort - min.sort
        })
        .map((item) => {
          return {
            value: item.id,
            tags: item.tags.map((it) => {
              return {
                tag_title: it
              }
            }),
            label: item.title
          }
        })
    }
    this.onGetTags()
    this.$nextTick(() => {
      this.setSort()
    })
  },
  methods: {
    async onGetTags() {
      const res = await commonData({ type: 'tag' })
      if (res.status_code === 1) {
        this.optionsList.tags = res.data.data
      }
    },
    async onGetRecommendPlaylet(value) {
      if (value) {
        const res = await commonData({ type: 'recommend_playlet', value })
        if (res.status_code === 1) {
          this.optionsList.custom_playlet = [...this.formData.custom_playlet, ...res.data.data]
        }
      }
    },
    onRemove(value) {
      const index = this.formData.custom_playlet.findIndex((item) => {
        return item.value === value
      })
      this.formData.custom_playlet.splice(index, 1)
    },
    close() {
      this.$emit('cancel')
    },
    commitData() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true
          const custom_playlet = this.formData.custom_playlet.map((item, index) => {
            return { playlet_id: item.value, sort: this.formData.custom_playlet.length - index }
          })
          playlet_recommendSave({ ...this.formData, custom_playlet }).then(
            (res) => {
              this.loading = false
              if (res.status_code === 1) {
                this.$message.success(res.msg)
                this.$emit('ok')
              }
            },
            (err) => {
              this.loading = false
            }
          )
        }
      })
    },
    setSort() {
      // ref一定跟table上面的ref一致
      const el = this.$refs.table.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost',
        setData: function (dataTransfer) {
          dataTransfer.setData('Text', '')
        },
        // 监听拖拽事件结束时触发
        onEnd: (evt) => {
          // 拖动行的前一行
          const targetRow = this.formData.custom_playlet.splice(evt.oldIndex, 1)[0]
          // 拖动行的后一行
          this.formData.custom_playlet.splice(evt.newIndex, 0, targetRow)
          const arr = []
          this.formData.custom_playlet.forEach((item, index) => {
            arr.push(item)
          })
          this.onrankSort(arr)
          // 这里的tableData是你table上面绑定的list
        }
      })
    },
    async onrankSort(arr) {
      this.formData.custom_playlet = []
      setTimeout(() => {
        this.$set(this.formData, 'custom_playlet', arr)
      }, 100)
    }
  }
}
</script>

<style lang="scss" scoped>
.form {
  padding: 20px;
  .form_bac {
    display: flex;
    height: 46px;
    align-items: center;
    background: #f2f3f5;
    border-radius: 4px;
    padding: 0 16px;
    span {
      font-size: 14px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      color: #1d2129;
    }
    .bac_label::before {
      content: '*';
      color: #f56c6c;
      margin-right: 4px;
      font-weight: 600;
    }
    .bac_input {
      width: 100px;
      margin: 0 10px;
    }
  }
  .model_border {
    height: 31px;
    margin-bottom: 10px;
    border-bottom: 1px solid #e5e6eb;
  }
  .model_title {
    display: flex;
    align-items: center;
    span {
      margin-right: 7px;
      font-size: 14px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 600;
      color: #1d2129;
    }
  }
  .model_title::before {
    content: ' ';
    display: inline-block;
    width: 3px;
    height: 15px;
    background: #00bf8a;
    margin-right: 10px;
  }
}
.drawerMain {
  width: 100%;
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  padding-bottom: 70px;
}
.content {
  width: 100%;
  padding: 20px;
}
.drag {
  cursor: pointer;
}
.dialog-footer {
  z-index: 1;
}
</style>